package com.financing.platform.web.api;

import com.financing.platform.common.Pager;
import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.ResultMap.STATUS;
import com.financing.platform.dto.*;
import com.financing.platform.service.*;
import com.financing.platform.util.*;
import com.financing.platform.vo.OrderManagerUserVO;
import com.financing.platform.vo.OrderPhoVO;
import com.financing.platform.vo.OrderVO;
import com.financing.platform.vo.ProductProfitAndRebateVO;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.axis.utils.SessionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import java.util.zip.ZipOutputStream;

@Controller("orderUpdateActionApi")
@RequestMapping("/api/orderUpdate")
@Scope("prototype")
public class OrderUpdateAction extends BaseAction{

	@Autowired
	IOrderService orderServiceImpl;

	@Autowired
	IProjectService projectServiceImpl;

	@Autowired
	private IFpOrderBizLogService fpOrderBizLogService;

	@Autowired
	private IFaUserService faUserServiceImpl;

	@Value("#{settings['fileBaseDir']}")
	private String fileBaseDir;


	@RequestMapping("/queryOrderList.shtml")
	@ResponseBody
	public ResultMap queryOrderList(HttpServletRequest request,
									HttpServletResponse response,OrderVO orderVo,Pager page) {

		try{

			page.setTotalCount(orderServiceImpl.queryOrderAllInfoCount(orderVo));

			orderVo.setBegin(page.getStartIndex());
			orderVo.setEnd(page.getPageSize());
			List<OrderVO> listOrder = orderServiceImpl.queryOrderList(orderVo);

			resultMap.setAttribute("orderList", listOrder);
			resultMap.setAttribute("page",page);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query order list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}

	@RequestMapping("/queryOrderByProIdList.shtml")
	@ResponseBody
	public ResultMap queryOrderByProIdList(HttpServletRequest request,
										   HttpServletResponse response,OrderVO orderVo,Pager page) {
		try{
			page.setTotalCount(orderServiceImpl.countOrderByProIdList(orderVo));

			orderVo.setBegin(page.getStartIndex());
			orderVo.setEnd(page.getPageSize());
			List<HashMap<String, String>> listOrder = orderServiceImpl.queryOrderByProIdList(orderVo);

			resultMap.setAttribute("orderList", listOrder);
			resultMap.setAttribute("page",page);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query order list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}

	@RequestMapping("/saveOrderIdList.shtml")
	@ResponseBody
	public ResultMap saveOrderIdList(HttpServletRequest request,
										   HttpServletResponse response,String idList) {
		try{

			FileUtil.saveFileInfo(idList,fileBaseDir+"/upload/order/orderIdList.txt");

			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query order list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}
	@RequestMapping("/getOrderIdList.shtml")
	@ResponseBody
	public ResultMap getOrderIdList(HttpServletRequest request,
									 HttpServletResponse response,OrderVO orderVo,Pager page) {
		try{
			String idList = FileUtil.getFileInfo(fileBaseDir+"/upload/order/orderIdList.txt");

			//idList = idList.replace("[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？a-zA-Z]",",");
			idList = idList.replace("\r\n","");
			orderVo.setOrderIdFile(idList);

			page.setTotalCount(orderServiceImpl.queryOrderAllInfoCount(orderVo));

			orderVo.setBegin(page.getStartIndex());
			orderVo.setEnd(page.getPageSize());
			List<OrderVO> listOrder = orderServiceImpl.queryOrderList(orderVo);

			resultMap.setAttribute("orderList", listOrder);
			resultMap.setAttribute("page",page);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query order list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}
	@RequestMapping("/queryOrderDateDetail.shtml")
	@ResponseBody
	public ResultMap queryOrderDateDetail(HttpServletRequest request,
									  HttpServletResponse response,OrderVO orderVo ,Integer pId) {

		try{

			Map<String ,Object> map =  new HashMap<String, Object>();

			if(pId == null) {

				List<OrderVO> listOrder = orderServiceImpl.queryOrderList(orderVo);

				if (listOrder.size() > 0) {
					orderVo = listOrder.get(0);
				}

				// 订单 预约时间
				map.put("orderCreateDate", DateUtil.getString(orderVo.getCreateDate(), DateUtil.DEFAULT_DATE_FORMAT));

				// 记录日志
				FpOrderBizLogDTO fpOrderBizLog = new FpOrderBizLogDTO();
				fpOrderBizLog.setBizId(orderVo.getOrderId());
				fpOrderBizLog.setBizType("order");
				fpOrderBizLog = fpOrderBizLogService.queryListGetFirst(fpOrderBizLog);
				if (fpOrderBizLog == null || fpOrderBizLog.getId() == null) {
					Map<String, Object> orderMap = new HashMap<String, Object>();
					orderMap.put("orderId", orderVo.getOrderId());
					orderMap.put("createDate", DateUtil.getString(orderVo.getCreateDate(), DateUtil.DEFAULT_DATE_FORMAT));
					fpOrderBizLog.setBizId(orderVo.getOrderId());
					fpOrderBizLog.setBizType("order");
					fpOrderBizLog.setBizData(JSONObject.fromObject(orderMap).toString());
					fpOrderBizLog.setDeleteTag("1");
					DTOdateSet.setUpdateInfo(fpOrderBizLog, request.getSession());
					DTOdateSet.setCreateInfo(fpOrderBizLog, request.getSession());
					fpOrderBizLogService.insert(fpOrderBizLog);
				}


				// 用户注册时间  认证时间
				FaUserDTO faUserDTO = new FaUserDTO();
				faUserDTO.setId(orderVo.getoFAId());
				faUserDTO = faUserServiceImpl.queryFaUserInfoView(faUserDTO);
				map.put("userCreateDate", DateUtil.getString(faUserDTO.getCreateDate(), DateUtil.DEFAULT_DATE_FORMAT));
				map.put("userAuthDate", DateUtil.getString(faUserDTO.getAuthDate(), DateUtil.DEFAULT_DATE_FORMAT));

				// 记录日志
				fpOrderBizLog.setId(null);
				fpOrderBizLog.setBizId(orderVo.getoFAId());
				fpOrderBizLog.setBizType("user");
				fpOrderBizLog = fpOrderBizLogService.queryListGetFirst(fpOrderBizLog);
				if (fpOrderBizLog == null || fpOrderBizLog.getId() == null) {
					Map<String, Object> jsonMap = new HashMap<String, Object>();
					jsonMap.put("createDate", DateUtil.getString(faUserDTO.getCreateDate(), DateUtil.DEFAULT_DATE_FORMAT));
					jsonMap.put("authDate", DateUtil.getString(faUserDTO.getAuthDate(), DateUtil.DEFAULT_DATE_FORMAT));
					fpOrderBizLog.setBizId(orderVo.getoFAId());
					fpOrderBizLog.setBizType("user");
					fpOrderBizLog.setBizData(JSONObject.fromObject(jsonMap).toString());
					fpOrderBizLog.setDeleteTag("1");
					DTOdateSet.setUpdateInfo(fpOrderBizLog, request.getSession());
					DTOdateSet.setCreateInfo(fpOrderBizLog, request.getSession());
					fpOrderBizLogService.insert(fpOrderBizLog);
				}

				//订单操作流水
				List<OrderFlowDTO> orderFlowList = orderServiceImpl.queryOrderFlowList(orderVo.getOrderId());

				OrderFlowDTO orderFlow = new OrderFlowDTO();
				Collections.sort(orderFlowList, orderFlow);

				Map<String, Object> jsonMap = new HashMap<String, Object>();
				for (OrderFlowDTO bean : orderFlowList) {
					bean.setFlowDateStr(DateUtil.getString(bean.getFlowDate(), DateUtil.DEFAULT_DATE_FORMAT));
					jsonMap.put(bean.getId().toString(), DateUtil.getString(bean.getFlowDate(), DateUtil.DEFAULT_DATE_FORMAT));
				}

				// 记录日志
				fpOrderBizLog.setId(null);
				fpOrderBizLog.setBizId(orderVo.getOrderId());
				fpOrderBizLog.setBizType("orderFlow");
				fpOrderBizLog = fpOrderBizLogService.queryListGetFirst(fpOrderBizLog);
				if (fpOrderBizLog == null || fpOrderBizLog.getId() == null) {
					fpOrderBizLog.setBizData(JSONObject.fromObject(jsonMap).toString());
					fpOrderBizLog.setBizId(orderVo.getOrderId());
					fpOrderBizLog.setBizType("orderFlow");
					DTOdateSet.setUpdateInfo(fpOrderBizLog, request.getSession());
					DTOdateSet.setCreateInfo(fpOrderBizLog, request.getSession());
					fpOrderBizLog.setDeleteTag("1");
					fpOrderBizLogService.insert(fpOrderBizLog);
				}


				resultMap.setAttribute("orderFlowList", orderFlowList);
				resultMap.setAttribute("orderVo", orderVo);
				resultMap.setAttribute("orderInfo", map);
			}else{
				//产品信息 -开始销售时间  - 结束销售时间  成立时间
				ProjectDTO projectDTO = new ProjectDTO();
				projectDTO.setId(pId );
				projectDTO = projectServiceImpl.queryProject(projectDTO);
				resultMap.setAttribute("saleTimeStart",DateUtil.getString(projectDTO.getpSaleTimeStart(),DateUtil.DEFAULT_DATE_FORMAT));
				resultMap.setAttribute("saleTimeEnd",DateUtil.getString(projectDTO.getpSaleTimeEnd(),DateUtil.DEFAULT_DATE_FORMAT));

				//获取 这个产品 最早的订单-最晚的订单
				Map<String,Object> minMaxMap = orderServiceImpl.queryOrderMaxMinDateByProductId(pId);

				resultMap.setAttribute("minOrderCreateDate",DateUtil.getString((Date) minMaxMap.get("minCreateDate"),DateUtil.DEFAULT_DATE_FORMAT));
				resultMap.setAttribute("maxOrderCreateDate",DateUtil.getString((Date) minMaxMap.get("maxCreateDate"),DateUtil.DEFAULT_DATE_FORMAT));

				// 记录日志
				FpOrderBizLogDTO fpOrderBizLog = new FpOrderBizLogDTO();
				fpOrderBizLog.setBizId(pId+"");
				fpOrderBizLog.setBizType("project");
				fpOrderBizLog = fpOrderBizLogService.queryListGetFirst(fpOrderBizLog);
				if(fpOrderBizLog == null || fpOrderBizLog.getId() == null){
					Map<String, Object> jsonMap = new HashMap<String, Object>();
					jsonMap.put("saleTimeStart",DateUtil.getString(projectDTO.getpSaleTimeStart(),DateUtil.DEFAULT_DATE_FORMAT));
					jsonMap.put("saleTimeEnd", DateUtil.getString(projectDTO.getpSaleTimeEnd(),DateUtil.DEFAULT_DATE_FORMAT));
					jsonMap.put("establishmentTime", DateUtil.getString(projectDTO.getpEstablishmentTime(),DateUtil.DEFAULT_DATE_FORMAT));
					fpOrderBizLog.setBizData(JSONObject.fromObject(jsonMap).toString());
					fpOrderBizLog.setBizId(pId+"");
					fpOrderBizLog.setBizType("project");
					fpOrderBizLog.setDeleteTag("1");
					DTOdateSet.setUpdateInfo(fpOrderBizLog, request.getSession());
					DTOdateSet.setCreateInfo(fpOrderBizLog, request.getSession());
					fpOrderBizLogService.insert(fpOrderBizLog);
				}
				resultMap.setAttribute("projectVo", projectDTO);
			}

			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query order list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}


		return resultMap;
	}

	@RequestMapping("/updateOrderDateDetail.shtml")
	@ResponseBody
	public ResultMap updateOrderDateDetail(HttpServletRequest request,
									  HttpServletResponse response,OrderVO orderVo ,Integer pId) {
		Map<String ,Object> map =  new HashMap<String, Object>();
		String updateBy ="system";
		if(null != request.getSession() && null != request.getSession().getAttribute("USER")){
			UserInfoDTO userinfo = (UserInfoDTO) request.getSession().getAttribute("USER");
			updateBy = userinfo.getUsername();
		}
		try{
			//获取订单信息
			List<OrderVO> listOrder = orderServiceImpl.queryOrderList(orderVo);

			if(listOrder.size()>0){
				orderVo = listOrder.get(0);
			}
			String dateparam = request.getParameter("dateparam");
			JSONObject json = JSONObject.fromObject(dateparam);

			pId = json.has("pId")?json.getInt("pId"):null;
			String userCreateDate = json.has("userCreateDate")?json.getString("userCreateDate"):null;
			String userAuthDate = json.has("userAuthDate")?json.getString("userAuthDate"):null;
			String orderCreateDate = json.has("orderCreateDate")?json.getString("orderCreateDate"):null;
			String saleTimeStart = json.has("saleTimeStart")?json.getString("saleTimeStart"):null;
			String saleTimeEnd = json.has("saleTimeEnd")?json.getString("saleTimeEnd"):null;
			String establishmentTime =json.has("establishmentTime")?json.getString("establishmentTime"):null;

			userCreateDate  = StringUtils.isBlank(userCreateDate)?null:userCreateDate;
			userAuthDate =  StringUtils.isBlank(userAuthDate)?null:userAuthDate;
			orderCreateDate =  StringUtils.isBlank(orderCreateDate)?null:orderCreateDate;
			saleTimeStart =  StringUtils.isBlank(saleTimeStart)?null:saleTimeStart;
			saleTimeEnd =  StringUtils.isBlank(saleTimeEnd)?null:saleTimeEnd;
			establishmentTime =  StringUtils.isBlank(establishmentTime)?null:establishmentTime;

			String orderFlowId = request.getParameter("orderFlowId");
			String orderFlow = request.getParameter("orderFlow");

		if(pId == null) {
			//用户信息
			String faUserId = orderVo.getoFAId();
			Map<String, Object> parameterMap = new HashMap<String, Object>();
			parameterMap.put("id", faUserId);
			parameterMap.put("faId", faUserId.toString());
			parameterMap.put("createDate", userCreateDate);
			parameterMap.put("authDate", userAuthDate);
			parameterMap.put("updateBy", updateBy);

			faUserServiceImpl.updateFaUserForVisit(parameterMap);

			FpOrderBizLogDTO fpOrderBizLog = new FpOrderBizLogDTO();
			fpOrderBizLog.setBizType("user");
			JSONObject userWapJson = JSONObject.fromObject(parameterMap);
			fpOrderBizLog.setBizData(userWapJson.toString());
			fpOrderBizLog.setBizId(faUserId);
			DTOdateSet.setUpdateInfo(fpOrderBizLog, request.getSession());
			DTOdateSet.setCreateInfo(fpOrderBizLog, request.getSession());
			fpOrderBizLog.setDeleteTag("1");
			fpOrderBizLogService.insert(fpOrderBizLog);

			//订单信息
			OrderByGaiZaoDTO orderByGaiZaoDTO = new OrderByGaiZaoDTO();
			orderByGaiZaoDTO.setId(orderVo.getOrderId());
			orderByGaiZaoDTO.setCreateDate(DateUtil.fullStringToDate(orderCreateDate));
			DTOdateSet.setUpdateInfo(orderByGaiZaoDTO, request.getSession());
			orderServiceImpl.updateOrder(orderByGaiZaoDTO);

			Map<String, Object> orderMap = new HashMap<String, Object>();
			orderMap.put("orderId", orderVo.getOrderId());
			orderMap.put("createDate", DateUtil.fullStringToDate(orderCreateDate));

			FpOrderBizLogDTO OrderBizLog = new FpOrderBizLogDTO();
			OrderBizLog.setBizType("order");
			JSONObject orderJson = JSONObject.fromObject(orderMap);
			OrderBizLog.setBizData(orderJson.toString());
			OrderBizLog.setBizId(orderVo.getOrderId());
			DTOdateSet.setUpdateInfo(OrderBizLog, request.getSession());
			DTOdateSet.setCreateInfo(OrderBizLog, request.getSession());
			OrderBizLog.setDeleteTag("1");
			fpOrderBizLogService.insert(OrderBizLog);

			//订单流水信息
			if (StringUtils.isNotBlank(orderFlowId)) {
				Map<String, Object> orderFlowMap = new HashMap<String, Object>();

				String[] orderFlowId_s = orderFlowId.split(",");
				String[] orderFlow_s = orderFlow.split(",");
				for (int i = 0; i < orderFlowId_s.length; i++) {
					String a = orderFlowId_s[i];
					String b = orderFlow_s[i];
					OrderFlowDTO orderFlowDTO = new OrderFlowDTO();
					orderFlowDTO.setId(Integer.valueOf(a));
					orderFlowDTO.setFlowDate(DateUtil.fullStringToDate(b));
					orderFlowDTO.setCreateDate(DateUtil.fullStringToDate(b));
					orderFlowDTO.setUpdateDate(DateUtil.fullStringToDate(b));
					orderServiceImpl.updateOrderFlow(orderFlowDTO);

					orderFlowMap.put(a,b);
				}
				FpOrderBizLogDTO OrderFlowBizLog = new FpOrderBizLogDTO();
				OrderFlowBizLog.setBizType("orderFlow");
				JSONObject orderFlowJson = JSONObject.fromObject(orderFlowMap);
				OrderFlowBizLog.setBizData(orderFlowJson.toString());
				OrderFlowBizLog.setBizId(orderVo.getOrderId());
				DTOdateSet.setUpdateInfo(OrderFlowBizLog, request.getSession());
				DTOdateSet.setCreateInfo(OrderFlowBizLog, request.getSession());
				OrderFlowBizLog.setDeleteTag("1");
				fpOrderBizLogService.insert(OrderFlowBizLog);

			}
		}else{
			//产品信息
			ProjectDTO projectDTO = new ProjectDTO();
			projectDTO.setId(pId);
			projectDTO.setpSaleTimeStart(DateUtil.StringToDate(saleTimeStart));
			projectDTO.setpSaleTimeEnd(DateUtil.StringToDate(saleTimeEnd));
			projectDTO.setpEstablishmentTime(DateUtil.StringToDate(establishmentTime));
			DTOdateSet.setUpdateInfo(projectDTO, request.getSession());
			projectServiceImpl.updateProject(projectDTO);

			Map<String, Object> projectMap = new HashMap<String, Object>();
			projectMap.put("saleTimeStart",DateUtil.StringToDate(saleTimeStart));
			projectMap.put("saleTimeEnd",DateUtil.StringToDate(saleTimeEnd));

			FpOrderBizLogDTO projectBizLog = new FpOrderBizLogDTO();
			projectBizLog.setBizType("project");
			JSONObject projectJson = JSONObject.fromObject(projectMap);
			projectBizLog.setBizData(projectJson.toString());
			projectBizLog.setBizId(pId+"");
			DTOdateSet.setUpdateInfo(projectBizLog, request.getSession());
			DTOdateSet.setCreateInfo(projectBizLog, request.getSession());
			projectBizLog.setDeleteTag("1");
			fpOrderBizLogService.insert(projectBizLog);
		}
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			log.info("End updateOrderDetail !");
		}catch(Exception e){
			log.error("update updateOrderDetail error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}


		return resultMap;


	}
}
